package com.cyyl.updater.download.receiver

import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.cyyl.updater.download.InstallApkHelper

/**
 * @author : Android-张康
 * created on: 2021/8/11 10:54
 * description: 下载监听
 */
class DownloadBroadcastReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent?) {
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE == intent?.action) {
            //下载完成，移除掉监听
            context.unregisterReceiver(this)
            installApk(context, intent)
        }
    }

    private fun installApk(context: Context, intent: Intent) {
        val downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
        if (downloadId != -1L) {
            val downloadManager: DownloadManager =
                context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
            downloadManager.getUriForDownloadedFile(downloadId)?.let { downloadFileUri ->
                InstallApkHelper.installApk(context, downloadFileUri)
            }
        }
    }
}